<!--
 * @Author: lilin_:）
 * @version: 1.0
 * @Descripttion: 供应商发票查询
 * @Date: 2021-08-27 09:09:37			
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-03-26 16:28:17
-->
<template>
	<div class="system-user-container">
		<el-card class="box-card">
			<div>
				<div class="my_btn_lay">
					<div class="my_flex my_btn" @click="searchEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--search"></i>
							<span>查找</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="resetEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--refresh"></i>
							<span>重置</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" @click="funnelEvent">
						<div class="my_flex_layout">
							<i class="vxe-icon--download"></i>
							<span>导出</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" v-if="selectFrom.isTale" @click="printTab">
						<div class="my_flex_layout">
							<i class="vxe-icon--print"></i>
							<span>打印</span>
						</div>
					</div>

					<div class="my_flex my_btn ml20" v-else @click="printTab2">
						<div class="my_flex_layout">
							<i class="vxe-icon--print"></i>
							<span>打印</span>
						</div>
					</div>
				</div>

				<vxe-form :data="selectFrom" title-align="left" prevent-submit title-colon>
					<vxe-form-item title="单位名称" field="tiunitNameme" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.tiunitNameme" placeholder="请选择单位名称" @change="change_unitName">
								<el-option v-for="item in selectFrom.unitsData" :key="item.id" :label="item.unitName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<vxe-form-item title="项目名称" field="type" span="6" :item-render="{}">
						<template #default="{ data }">
							<el-select style="width: 100%" clearable filterable v-model="data.projectID" placeholder="请选择项目名称">
								<el-option v-for="item in selectFrom.projectData" :key="item.id" :label="item.contractName" :value="item.id"> </el-option>
							</el-select>
						</template>
					</vxe-form-item>

					<!-- <vxe-form-item align="right" span="24" collapse-node>
						<template #default>
							<vxe-button status="primary" content="搜索" @click="searchEvent"></vxe-button>
							<vxe-button content="重置" @click="resetEvent"></vxe-button>
						</template>
					</vxe-form-item> -->
				</vxe-form>
			</div>

			<!-- <vxe-toolbar ref="xToolbar" custom>
				<template #buttons> </template>
				<template #tools>
					<vxe-button type="text" icon="vxe-icon--print" class="tool-btn" @click="printTab" v-if="selectFrom.isTale"></vxe-button>

					<vxe-button type="text" icon="vxe-icon--print" class="tool-btn" @click="printTab2" v-else></vxe-button>

					<vxe-button type="text" icon="vxe-icon--download" class="tool-btn" @click="funnelEvent"></vxe-button>
				</template>
			</vxe-toolbar> -->

			<!-- @edit-closed="editClosedEvent" -->
			<!-- :edit-config="{ trigger: 'click', mode: 'row' }" -->
			<!-- 单位表格 -->
			<vxe-table
				:scroll-x="{ enabled: false }"
				:scroll-y="{ enabled: false }"
				class="mytable-style"
				v-if="selectFrom.isTale"
				align="center"
				border
				keep-source
				:height="780"
				ref="xTable1"
				:export-config="{}"
				resizable
				show-overflow
				:data="tableData"
				@checkbox-all="selectAllChangeEvent1"
				@checkbox-change="selectChangeEvent1"
				show-footer
				:footer-method="footerMethod"
			>
				<!-- <vxe-column align="center" type="checkbox" width="60"></vxe-column> -->
				<vxe-column align="center" type="seq" title="序号" width="60"></vxe-column>

				<!-- <vxe-column type="seq" width="60"></vxe-column> -->
				<vxe-column field="contractName" title="项目名称" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="excludingTaxInvoiced" title="不含税金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.excludingTaxInvoiced) }}</template>
				</vxe-column>
				<vxe-column field="inputTax" title="进项税" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.inputTax) }}</template>
				</vxe-column>
				<vxe-column field="taxIncludedInvoiced" title="发票金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.taxIncludedInvoiced) }}</template>
				</vxe-column>
				<vxe-column field="payment" title="支付金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.payment) }}</template>
				</vxe-column>
				<vxe-column field="balance" title="余额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.balance) }}</template>
				</vxe-column>
			</vxe-table>

			<!-- 当是两参数的时候是单位的表 -->
			<vxe-table
				class="mytable-style"
				:scroll-x="{ enabled: false }"
				:scroll-y="{ enabled: false }"
				v-else
				border
				align="center"
				keep-source
				:height="780"
				ref="xTable1"
				:export-config="{}"
				resizable
				show-overflow
				:data="tableData"
				@checkbox-all="selectAllChangeEvent1"
				@checkbox-change="selectChangeEvent1"
				show-footer
				:footer-method="footerMethod2"
			>
				<vxe-column align="center" type="checkbox" width="60"></vxe-column>
				<vxe-column align="center" type="seq" title="序号" width="60"></vxe-column>

				<vxe-column field="timeStr" title="日期" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="billMoney" title="开票金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.billMoney) }}</template>
				</vxe-column>

				<vxe-column field="ticketDebit" title="收到票据" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.ticketDebit) }}</template>
				</vxe-column>
				<vxe-column field="bankDebit" title="收到转账" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.bankDebit) }}</template>
				</vxe-column>

				<vxe-column field="contractUnit" title="单位名称" :edit-render="{ name: 'input', attrs: { type: 'text' } }"></vxe-column>
				<vxe-column field="excludingTaxInvoiced" title="不含税金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.excludingTaxInvoiced) }}</template>
				</vxe-column>
				<vxe-column field="inputTax" title="进项税" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.inputTax) }}</template>
				</vxe-column>
				<vxe-column field="invoiceAmount" title="发票金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.invoiceAmount) }}</template>
				</vxe-column>
				<vxe-column field="payment" title="支付金额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.payment) }}</template>
				</vxe-column>
				<vxe-column field="difference" title="发票差额" :edit-render="{ name: 'input', attrs: { type: 'text' } }">
					<template v-slot="{ row }">{{ transitionNumber(row.difference) }}</template>
				</vxe-column>
			</vxe-table>
		</el-card>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, ref, toRaw, onMounted, nextTick } from 'vue';

import { ElMessage, ElMessageBox } from 'element-plus';
import { axios_SelList, axios_SelListAll } from '/@/api/basicsUrl/index';
import { axios_contactsAdd } from '/@/api/addressBook/index';
import { axios_selListByPaymentUnitId } from '/@/api/customerDetails/index';

import { axios_supplierselList } from '/@/api/invoiceQuery/index'; //供应商发票查询
import { transitionNumber } from '/@/utils/transitionNumber';

import { axios_selListByContractUnit } from '/@/api/invoiceLedger/index';

export default {
	name: 'InvoiceQuery',
	setup() {
		const xTable1 = ref({} as VxeTableInstance);
		const xToolbar = ref({} as VxeToolbarInstance);

		// 打印样式
		// 打印样式
		const printStyle = `
            .title {
              text-align: center;
            }
            .my-list-row {
              display: inline-block;
              width: 100%;
            }
            .my-list-col {
              float: left;
              width: 33.33%;
              height: 28px;
              line-height: 28px;
            }
            .my-top,
            .my-bottom {
              font-size: 12px;
            }
            .my-top {
              margin-bottom: 5px;
            }
            .my-bottom {
              margin-top: 30px;
              text-align: right;
            }
            `;

		// 打印顶部内容模板
		const topHtml = `
            <h1 class="title">出货单据</h1>
            <div class="my-top">
              <div class="my-list-row">
                <div class="my-list-col">商品名称： </div>
                <div class="my-list-col">发货单号：X2665847132654</div>
                <div class="my-list-col">发货日期：2020-09-20</div>
              </div>
              <div class="my-list-row">
                <div class="my-list-col">收货姓名： </div>
                <div class="my-list-col">收货地址：火星第七区18号001</div>
                <div class="my-list-col">联系电话：10086</div>
              </div>
            </div>
            `;

		// 打印底部内容模板
		const bottomHtml = `
            <div class="my-bottom">
              <div class="my-list-row">
                <div class="my-list-col"></div>
                <div class="my-list-col">创建人： </div>
                <div class="my-list-col">创建日期：2020-09-20</div>
              </div>
            </div>
            `;

		const state: any = reactive({
			selectFrom: {
				tiunitNameme: '', //单位名称穿ID
				time: [], //时间搜索
				// type: '', //单位类型1供应商2客户3公司员工
				// typeArry: [
				// 	{ label: '供应商', value: '1' },
				// 	{ label: '客户', value: '2' },
				// 	{ label: '公司员工', value: '3' },
				// ], //单位类型1供应商2客户3公司员工
				unitsData: [], //单位搜索的数据和联系人一样
				projectData: [], //项目数据
				projectID: '', //项目id
			},
			tableData: [], //表格数据
			tableData2: [], //单位名称表格
			data: {
				excludingTaxInvoiced: 0,
				inputTax: 0,
				taxIncludedInvoiced: 0,
				payment: 0,
				balance: 0,
				billMoney: 0,
				ticketDebit: 0,
				bankDebit: 0,
				invoiceAmount: 0,
				difference: 0,
			},
			isTale: true, //是默单位表格
		});

		const selectAllChangeEvent1: VxeTableEvents.CheckboxAll = ({ checked, records }: any) => {
			console.log(checked ? '所有勾选事件' : '所有取消事件', records);
		};

		const selectChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked, records }: any) => {
			console.log(checked ? '勾选事件' : '取消事件', records);
		};

		/**
		 * @Author: lilin_:）
		 * @name: 获取单位名称
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getClientSelList = async () => {
			let resData: any = await axios_SelListAll();
			state.selectFrom.unitsData = resData.obj;
		};
		// 查询当前的项目名称全部
		const getProjectData = async () => {
			let resData: any = await axios_selListByContractUnit();

			state.selectFrom.projectData = resData.obj;
			// console.log(  toRaw(resData) , '我三项目的数据');
		};

		/**
		 * @Author: lilin_:）
		 * @name:
		 * @Descripttion: 搜索
		 * @param {*}
		 * @return {*}
		 */
		const searchEvent: VxeFormEvents.Submit = async () => {
			// VXETable.modal.message({ content: '查询事件', status: 'info' });
			// 判断是展示那个表格

			console.log(state.selectFrom.tiunitNameme, '111111111');
			console.log(state.selectFrom.projectID, '222222222222');

			if (state.selectFrom.tiunitNameme != '' && state.selectFrom.projectID != '') {
				console.log('我两个都传递了参数');
				state.selectFrom.isTale = false; //项目表
			} else if (state.selectFrom.projectID != '') {
				state.selectFrom.isTale = false; //项目表
			} else {
				state.selectFrom.isTale = true; //单位表
				console.log('查询单位的表');
			}

			await getClientSelList_user();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 重置搜索表单
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const resetEvent: VxeFormEvents.Reset = async () => {
			state.selectFrom.tiunitNameme = ''; //单位名称
			state.selectFrom.projectID = ''; //项目数据
			state.selectFrom.projectData = []; //项目数据
			await getProjectData(); //所有项目
			await getClientSelList_user();
			// VXETable.modal.message({ content: '重置事件', status: 'info' });
		};

		onMounted(() => {
			getClientSelList(); //单位名称
			getProjectData(); //所有项目
			// getClientSelList_user(); //搜索

			// let a = GenNonDuplicateID()
			// console.log(a)
		});

		//实时更新
		const editClosedEvent: VxeTableEvents.EditClosed = ({ row, column }) => {
			console.log(toRaw(column), '11111');
			let getRow: any = row;

			// console.log(toRaw(getRow, '111111111'));
			axios_contactsAdd(getRow).then((res) => {
				// console.log(res, '111111111');
				if (res.code == 200) {
					ElMessage.success({
						message: `${res.msg}`,
						type: 'success',
					});
				}
			});

			const $table = xTable1.value;
			const field = column.property;
			const cellValue = row[field];
			// 判断单元格值是否被修改;
			// if ($table.isUpdateByRow(row, field)) {
			// 	setTimeout(() => {
			// 		VXETable.modal.message({
			// 			content: `局部保存成功！ ${field}=${cellValue}`,
			// 			status: 'success',
			// 		});
			// 		// 局部更新单元格为已保存状态
			// 		$table.reloadRow(row, null, field);
			// 	}, 300);
			// }
		};

		/**
		 * @Author: lilin_:）
		 * @name: 关联表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		nextTick(() => {
			// 将表格和工具栏进行关联
			const $table = xTable1.value;
			const $toolbar = xToolbar.value;
			$table.connect($toolbar);
		});

		/**
		 * @Author: lilin_:）
		 * @name: 新增空白行
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const addDefaultBlank = () => {
			let addArry = defaultBlankData.map((item: any) => {
				return {
					...item,
					...{
						webid: GenNonDuplicateID(),
					},
				};
			});
			state.invoiceLedgerTableData = JSON.parse(JSON.stringify([...state.invoiceLedgerTableData, ...addArry]));
			console.log(toRaw(state.invoiceLedgerTableData), '11111111111');
			ElMessage.success({
				message: '新增1行空白栏',
				type: 'success',
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 删除数据
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const deleteTable: any = async () => {
			let webAddArry: any = [];
			let reeData: any = [];
			state.selectData.forEach((item: any) => {
				if (item.iswebAdd == true) {
					webAddArry.push(item);
				} else {
					reeData.push(item);
				}
			});
			// 判断前端数据是否有值
			let webDelet = () => {
				if (webAddArry.length != 0) {
					// 前端删除
					state.invoiceLedgerTableData = state.invoiceLedgerTableData.filter((item: any) => {
						return !webAddArry.find((_item: any) => _item.webid === item.webid);
					});
					// 删除方法2
					// 		state.invoiceLedgerTableData=arr;
					// 	const arr=state.invoiceLedgerTableData;
					// 		console.log(JSON.parse(JSON.stringify(arr)),'aaaaaaaaaaaaaaaaaaaaa');
					// webAddArry.forEach((item:any) => {
					// 			arr.forEach((_item,_index) => {
					// 					if(_item.webid===item.webid){
					// 							arr.splice(_index,1)
					// 					}
					// 			});
					// });
					// state.invoiceLedgerTableData=JSON.parse(JSON.stringify(arr))
				}
			};

			let resDelet = async () => {
				if (reeData.length != 0) {
					let { code }: object = await axios_billDell(
						reeData.map((item: any) => {
							return item.id;
						})
					);

					// console.log(code, '11111111');
					if (code == 200) {
						getInvoiceLedgerTableData();
					}
				}
			};
			await resDelet();
			await webDelet();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 高级导出功能
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const funnelEvent = () => {
			const $table = xTable1.value;
			$table.openExport();
		};

		/**
		 * @Author: lilin_:）
		 * @name: 打印表格
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const printTab = () => {
			const $table = xTable1.value;
			$table.print({
				sheetName: '供应商发票查询',
				style: printStyle, //自定义样式
				columns: [
					{ field: 'contractName' },
					{ field: 'excludingTaxInvoiced' },
					{ field: 'inputTax' },
					{ field: 'taxIncludedInvoiced' },
					{ field: 'payment' },
					{ field: 'balance' },
				],
				beforePrintMethod: ({ content }) => {
					// 拦截打印之前，返回自定义的 html 内容
					// return topHtml + content + bottomHtml;
					return content;
				},
			});
		};

		const printTab2 = () => {
			const $table = xTable1.value;
			$table.print({
				sheetName: '供应商发票查询',
				style: printStyle, //自定义样式
				columns: [
					{ field: 'timeStr' },
					{ field: 'billMoney' },
					{ field: 'ticketDebit' },
					{ field: 'bankDebit' },
					{ field: 'contractUnit' },
					{ field: 'excludingTaxInvoiced' },
					{ field: 'inputTax' },
					{ field: 'invoiceAmount' },
					{ field: 'payment' },
					{ field: 'difference' },
				],
				beforePrintMethod: ({ content }) => {
					// 拦截打印之前，返回自定义的 html 内容
					// return topHtml + content + bottomHtml;
					return content;
				},
			});
		};

		/**
		 * @Author: lilin_:）
		 * @name: 查询供应商发票
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const getClientSelList_user = async () => {
			// console.log( toRaw(state.selectFrom.projectID) ,'projectID')
			let { code, obj, data } = await axios_supplierselList({
				contractUnitId: state.selectFrom.tiunitNameme,
				contractId: state.selectFrom.projectID,
			});
			if (code == 200) {
				state.tableData = obj;
				state.data = data; //合计的数据
			}
		};

		/**
		 * @Author: lilin_:）
		 * @name:
		 * @Descripttion:切换单位名称事件
		 * @param {*} value
		 * @return {*}
		 */
		const change_unitName = async (value: any) => {
			console.log(value, 'value我是拿到的');
			await get_selListByContractUnitId(value);
			state.selectFrom.projectID = '';
		};

		/**
		 * @Author: lilin_:）
		 * @name: 通过单位名称查询项目名称
		 * @Descripttion:
		 * @param {*}
		 * @return {*}
		 */
		const get_selListByContractUnitId = async (id: any) => {
			let { code, obj } = await axios_selListByPaymentUnitId({
				contractUnitId: id,
			});
			if (code == 200) {
				state.selectFrom.projectData = obj;
			}
			// state.selectFrom.projectID = [];

			// console.log(obj, '11111111111111111111');
		};

		// 合计
		const footerMethod: VxeTablePropTypes.FooterMethod = ({ columns, data }) => {
			return [
				columns.map((column, columnIndex) => {
					// 当为true 第一个表格的时候
					if (columnIndex === 2) {
						return '合计';
					}
					if (columnIndex === 3) {
						return `${state.data.excludingTaxInvoiced} `;
					}
					if (columnIndex === 4) {
						return `${state.data.inputTax} `;
					}
					if (columnIndex === 5) {
						return `${state.data.taxIncludedInvoiced} `;
					}
					if (columnIndex === 6) {
						return `${state.data.payment} `;
					} else if (columnIndex === 7) {
						return `${state.data.balance} `;
						// return `共 ${countAllAmount(data)} `;
					}
					return '';
				}),
			];
		};

		const footerMethod2: VxeTablePropTypes.FooterMethod = ({ columns, data }) => {
			return [
				columns.map((column, columnIndex) => {
					if (columnIndex === 2) {
						return '合计';
					}
					if (columnIndex === 3) {
						return `${state.data.billMoney} `;
					}
					if (columnIndex === 4) {
						return `${state.data.ticketDebit} `;
					}
					if (columnIndex === 5) {
						return `${state.data.bankDebit} `;
					}
					if (columnIndex === 7) {
						return `${state.data.excludingTaxInvoiced} `;
					}
					if (columnIndex === 8) {
						return `${state.data.inputTax} `;
					}
					if (columnIndex === 9) {
						return `${state.data.invoiceAmount} `;
					}
					if (columnIndex === 10) {
						return `${state.data.payment} `;
					}
					if (columnIndex === 11) {
						return `${state.data.difference} `;
					}
					return '';
				}),
			];
		};

		return {
			...toRefs(state),
			editClosedEvent, //实时更新
			xToolbar, //关联表格
			xTable1, //表格
			addDefaultBlank, //新增空白行
			deleteTable, //删除数据
			funnelEvent, //导出数据
			printTab, //打印
			printTab2, //打印2
			change_unitName, //切换单位名称
			getClientSelList,
			footerMethod, //合计表格
			footerMethod2, //合计表格

			selectAllChangeEvent1,
			selectChangeEvent1,

			searchEvent,
			resetEvent,
			transitionNumber,
		};
	},
};
</script>

<style scoped lang="scss"></style>
